﻿using java.lang;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Windows;
using yzrilyzr.FAQ.client;
using yzrilyzr.FAQ.constants;
using yzrilyzr.FAQ.protocol;
using yzrilyzr.FAQ.utils;
using yzrilyzr.util;
using Exception = System.Exception;
using File = java.io.File;

namespace FAQ_UI
{
	/// <summary>
	/// AccountWindow.xaml 的交互逻辑
	/// </summary>
	public partial class AccountWindow : Window, System.ComponentModel.INotifyPropertyChanged

	{
		private List<FAQID> list = new List<FAQID>();
		private Logger logger = new Logger("Main");

		public AccountWindow()
		{
			InitializeComponent();
			this.DataContext = this;
			update();
			//new TestWindow().Show();
			//new SafeForm().Show();
		}

		public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

		public List<FAQID> BDataSource
		{ get { return list; } }

		public Holder BHolder
		{ get { return new Holder(); } }

		protected void OnPropertyChanged(string propertyName)
		{
			logger.i(propertyName);
			if (PropertyChanged != null)
			{
				PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
			}
		}

		private void update()
		{
			list.Clear();
			File f = new File(FAQClient.getClientPath());
			File[] fs = f.listFiles();
			foreach (File j in fs)
			{
				if (!j.isDirectory()) continue;
				bool check = false;
				int uid = 0;
				try
				{
					uid = Integer.parseInt(j.getName());
					check = FAQClient.checkAccount(uid);
				}
				catch (NumberFormatException e)
				{
					continue;
				}
				catch (Exception e)
				{
					check = false;
				}
				if (check)
				{
					DB var2 = DB.from(j.getAbsolutePath() + "/userdata", FAQTypeMap.INSTANCE);
					FAQID var3 = var2.getUUID(D.UUID, Wrap.w(uid));
					list.Add(var3);
				}
				else list.Add(new FAQID(-1, uid));
			}
		}

		protected override void OnClosed(System.EventArgs e)
		{
			base.OnClosed(e);
			if (Application.Current.Windows.Count == 0 && FAQUtil.client == null)
			{
				App.Current.Shutdown();
				Environment.Exit(0);
			}
		}

		public class Holder : FriendHolder
		{
			public override ViewHolder newInstance()
			{
				return new Holder();
			}

			public override void set(int i, object fAQID, IList datalist)
			{
				FAQID faqid = (FAQID)fAQID;
				Name.Text = FAQClient.getName(faqid);
				Description.Text = FAQUtil.getDescription(faqid);
				if (faqid.getMost() == -1) Description.Text = "帐户校验失败";
				Avatar.Drawable = FAQUtil.getAvatar(faqid);
			}
		}

		private void newAccount(object sender, RoutedEventArgs e)
		{
			new NewAccount().ShowDialog();
			update();
			myListView.notifyDataChanged();
		}

		private void myListView_ItemClick(object sender, OnItemClickEvent e)
		{
			FAQUtil.eventBus.syncSend(new BinMsgPack(App.OPEN_ACCOUNT).setTo(list[e.index]));
			new MainWindow(list[e.index]).Show();
			Close();
		}
	}
}